package com.study.lxy.netty.nio;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class SimpleClient {
    public static void main(String[] args) throws Exception {
        Thread t = new Thread(new SimpleClientRunner("127.0.0.1", 8080));
        t.start();
        t.join();
    }
}

class SimpleClientRunner implements Runnable{
    private static final Logger logger = LoggerFactory.getLogger(SimpleClient.class);

    private String ip;
    private int port;
    private Selector selector;
    private SocketChannel socketChannel;

    public SimpleClientRunner(String ip, int port){
        this.ip = ip;
        this.port = port;
        init();
    }

    public void run() {
        try {
            // 尝试建立连接
            boolean connected = connect();
            // 如果连接已建立，则写语句
            if(connected){
                doWrite(socketChannel);
            }
            // 尝试去获取激活的事件
            while (true){
                selector.select(1000);
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()){
                    SelectionKey key = iterator.next();
                    iterator.remove();
                    if(key.isValid()){
                        SocketChannel sc = (SocketChannel) key.channel();
                        if(sc == socketChannel){
                            logger.info("is the same channel...");
                        }
                        if(key.isConnectable()){
                            if(sc.finishConnect()) {
                                sc.register(selector, SelectionKey.OP_READ);
                                doWrite(sc);
                            } else {
                                System.exit(-1);
                            }
                        } else if(key.isReadable()){
                            read(sc, key);
                        }
                    }
                }
            }
        } catch (Exception e){
            e.printStackTrace();
            System.exit(-1);
        }
    }

    private void init(){
        try {
            selector = Selector.open();
            socketChannel = SocketChannel.open();
            socketChannel.configureBlocking(false);
        } catch (Exception e){
            e.printStackTrace();
            System.exit(-1);
        }
    }

    private boolean connect() throws Exception {
        if (socketChannel.connect(new InetSocketAddress(ip, port))) {
            logger.info("connect success....");
            socketChannel.register(selector, SelectionKey.OP_READ);
            logger.info("register read event...");
            return true;
        } else {
            logger.info("register connect event....");
            socketChannel.register(selector, SelectionKey.OP_CONNECT);
            return false;
        }
    }

    private void doWrite(SocketChannel sc) throws Exception{
        String message = "liuxingyi043";
        byte[] bytes = message.getBytes();
        ByteBuffer byteBuffer = ByteBuffer.allocate(bytes.length);
        byteBuffer.put(bytes);
        byteBuffer.flip();
        logger.info("send message : {}", message);
        sc.write(byteBuffer);
    }

    private void read(SocketChannel sc, SelectionKey key) throws Exception{
        ByteBuffer byteBuffer = ByteBuffer.allocate(2048);
        int size = sc.read(byteBuffer);
        if(size > 0) {
            byteBuffer.flip();
            byte[] bytes = new byte[byteBuffer.remaining()];
            byteBuffer.get(bytes);
            String resp = new String(bytes, "UTF-8");
            logger.info("message receive : {}", resp);
        } else if(size < 0){
            key.cancel();
            sc.close();
        }
    }
}
